﻿using System;
using Microsoft.Xna.Framework.Audio;

namespace Vixen.Framework
{
    /// <summary>This class encapsulates variables and methods for sound effect handling.</summary>
    public class AudioEffect
    {
        private readonly SoundEffectInstance _instance;
        private bool _disposed;
        private SoundEffect _sound;

        /// <summary>Loads an asset in the form of a SoundEffect.</summary>
        /// <param name="assetName">The name of the asset to load.</param>
        public AudioEffect(string assetName)
        {
            _sound = Engine.LoadAsset<SoundEffect>(assetName);
            _instance = _sound.CreateInstance();
        }

        /// <summary>The duration of the audio file.</summary>
        public TimeSpan Duration
        {
            get
            {
                if (!_disposed)
                {
                    return _sound.Duration;
                }
                return new TimeSpan(-1);
            }
        }

        /// <summary>The title of the Audio file that's associated to the AudioEffect.</summary>
        public string Name
        {
            get
            {
                if (!_disposed)
                {
                    return _sound.Name;
                }
                return null;
            }
        }

        /// <summary>Whether the AudioEffect is supposed to loop or not.</summary>
        public bool Looping
        {
            get
            {
                if (!_disposed)
                {
                    if (_instance.IsLooped)
                        return true;
                    return false;
                }
                return false;
            }
            set
            {
                if (!_disposed)
                    _instance.IsLooped = value;
            }
        }

        /// <summary>Whether the AudioEffect has been disposed or not.</summary>
        public bool IsDisposed
        {
            get { return _disposed; }
        }

        /// <summary>Plays the audio file associated to the AudioEffect.</summary>
        public void Play()
        {
            if (!_disposed)
                _sound.Play();
        }

        /// <summary>Disposes of any resources used by the AudioEffect.</summary>
        public void Dispose()
        {
            if (!_disposed)
            {
                _instance.Dispose();
                _sound = null;
                _disposed = true;
            }
        }
    }
}